<template>
  <el-collapse v-model="showCollapse.TF_binding">
    <div>
      <p style="font-size: 16px;font-weight: bold;text-align: justify;padding:0 20px" v-if="form.type === 'tf'">
        * This page provides comprehensive information about the input TF (
        <span style="color: red">{{form.tf}}</span>
        ), including the disruption of DNA affinity by ASM, the relationship between this disruption and methylation imbalance, and the co-localization of ChIP-seq peak with ASM.

      </p>
      <p style="font-size: 16px;font-weight: bold;text-align: justify;padding:0 20px" v-else>
        * This page provides comprehensive information about the input snv (
        <span style="color: red">{{form.snv}}</span>
        ), including the disruption of DNA affinity by ASM, the relationship between this disruption and methylation imbalance, and the co-localization of ChIP-seq peak with ASM.

      </p>
    </div>
    <el-collapse-item name="1">
      <template #title>
        <div class="card-title">
          Affinity disruption
        </div>
      </template>
      <div style="margin: 10px;">
        <el-row justify="space-around">
          <el-col :span="23">
            <Table
                :column="TF_binding_table.column"
                :searchKey="tfTable1"
                :size="7"
                :api-key="'analysis_tf'"
            ></Table>
          </el-col>
        </el-row>
      </div>
    </el-collapse-item>
    <el-collapse-item name="2" v-if="form.type === 'tf'">
      <template #title>
        <div class="card-title">
          Methylation imbalance vs affinity disruption
        </div>
      </template>
      <div style="margin: 10px;">
        <el-row justify="space-around">
          <el-col :span="23">
            <el-tabs type="card">
              <el-tab-pane label="Methylation imbalance">
                <el-row justify="space-between">
                  <el-col :span="10">
                    <span style="font-size: 16px;font-weight: bold;">Motif:&nbsp</span>
                    <el-select v-model="Motif"
                               @change="getPlot(tfTable1.tf,tfTable1.health,tfTable1.tissue,tfTable1.motif,Motif,tfTable1.snv,tfTable1.type)"
                               placeholder="Select" style="width: 240px;margin-bottom: 10px">
                      <el-option
                          v-for="item in motifOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                    <div v-loading="motifLoading">
<!--                      <iframe-->
<!--                          :src="tfPlot"-->
<!--                          width="100%"-->
<!--                          height="500"-->
<!--                      />-->
                      <analysis1_chart :plotdata="tfPlot"></analysis1_chart>
                    </div>

                  </el-col>
                  <el-col :span="11">
<!--                     v-loading="motifLoading"-->
                    <div>
                    <el-descriptions
                        :column="1"
                        size="large"
                        border
                    >
                      <el-descriptions-item label="All Motifs">
                        <div style="height: 30px;line-height: 35px">{{ TF_motif.tabledata[0]['motifs'] }}</div>
                      </el-descriptions-item>
                      <el-descriptions-item label="All SNVs">
                        <el-tooltip
                            class="box-item"
                            effect="light"
                            :content="'<p style=\'width: 400px;overflow: scroll;max-height: 400px\'>'+TF_motif.tabledata[0]['snv']+'</p>'"
                            raw-content
                            placement="top"
                        >
                          <p style="height: 300px;line-height: 20px;width: 450px;overflow: hidden;word-wrap:break-word;text-overflow:ellipsis; ">
                            {{ TF_motif.tabledata[0]['snv'] }}
                          </p>
                        </el-tooltip>
                      </el-descriptions-item>
                      <el-descriptions-item label="Motif logo" >
                        <img v-if="TF_motif.tabledata[0].plot !== null" :src="TF_motif.tabledata[0]['plot']" :alt="Motif.label" width="300" height="100">
                        <!-- <img :src="require('@/assets/test/test2.png')" width="300" height="100"> -->
                        <span v-if="TF_motif.tabledata[0].plot === null">Null</span>
                      </el-descriptions-item>
                    </el-descriptions>
                    </div>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="ASMs alterating the affinity">
                <Table
                    :column="TF_snv_alterating_table.column"
                    :table-all-data="TF_snv_alterating_table.tableData"
                    :searchKey="tfTable1"
                    :api-key="'analysis_tf_snv_alterating'"
                ></Table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>
    </el-collapse-item>
    <el-collapse-item name="2" v-else>
      <template #title>
        <div class="card-title">
          ASMs alterating the affinity
        </div>
      </template>
      <div style="margin: 10px;">
        <el-row justify="space-around">
          <el-col :span="23">
            <Table
                :column="TF_snv_alterating_table.column"
                :table-all-data="TF_snv_alterating_table.tableData"
                :searchKey="tfTable1"
                :api-key="'analysis_tf_snv_alterating'"
            ></Table>
          </el-col>
        </el-row>
      </div>
    </el-collapse-item>
    <el-collapse-item name="3">
      <template #title>
        <div class="card-title">
          Colocalization with ASMs
        </div>
      </template>
      <div style="margin: 10px;">
        <el-row justify="space-around">
          <el-col :span="23">
            <Table
                :column="TF_chip_seq_binding_table.column"
                :searchKey="tfTable1"
                :api-key="'analysis_tf_chip-seq'"
            ></Table>
          </el-col>
        </el-row>
      </div>
    </el-collapse-item>
  </el-collapse>
</template>

<script>
import {reactive,toRefs} from "@vue/reactivity";
import analysis1_chart from "@/components/chart/analysis1_chart.vue"
import {watch,ref} from "vue"
import {Table,Table_col} from "@/components/table/index"
import filetool from "@/tool/Filetool"
import {useRoute} from "vue-router";
import api from "@/api/api";

export default {
  name: "TF_binding_detail",
  components:{
    Table,Table_col,analysis1_chart
  },
  setup(){
    const route = useRoute()
    const form = JSON.parse(route.query.form)

    console.log(form)
    const data = reactive({
      showCollapse: {
        TF_binding: ['1','2','3'],
      },
      TF_binding_table: {
        column:[
          // {name: 'TF Name',value:'tf',href: false},
          {name: 'Motif',value:'motif',href: false},
          {name: 'TF',value:'tf',href: false},
          {name: 'SNV',value:'snv',href: false},
          {name: 'Affinity change',value:'affinity_score_change',href: false},
          {name: 'FDR',value:'fdr',href: false},
          {name: 'TF class',value:'homoMotifInfoFinal.homoMotifInfoFinalClass',href: false},
          {name: 'TF family',value:'homoMotifInfoFinal.family',href: false},
          {name: 'Source',value:'homoMotifInfoFinal.source',href: false},
          {name: 'Vlidation',value:'homoMotifInfoFinal.vlidation',href: false},
          {name: 'Pubmed',value:'homoMotifInfoFinal.pubmed',href: false},
        ],
        tableData: []
      },
      TF_snv_alterating_table: {
        column:[
          // {name: 'Motif',value:'selectMotif',href: false},
          // {name: 'TF',value:'selectTf',href: false},
          {name: 'SNV',value:'idInDbsnp',href: false},
          {name: 'Chr',value:'chr',href: false},
          {name: 'SNV position',value:'snpPos',href: false},
          {name: 'CpG position',value:'cpgPos',href: false},
          // {name: 'CpG_ID',value:'cpgId',href: false},
          {name: 'Ref',value:'refInDbsnp',href: false},
          {name: 'Alt',value:'alternateAllele',href: false},
          {name: 'Alt in dbSNP',value:'altInDbsnp',href: false},
          {name: 'Ref coverage',value:'referenceCoverage',href: false},
          {name: 'Ref Meth',value:'referenceMeth',href: false},
          {name: 'Ref β value',value:'refBeta',href: false},
          {name: 'Alt coverage',value:'alternateCoverage',href: false},
          {name: 'Alt Meth',value:'alternateMeth',href: false},
          {name: 'Alt β value',value:'altBeta',href: false},
          {name: 'ASM p-value',value:'pValue',href: false},
          {name: 'ASM q-value',value:'qValue',href: false},
          {name: 'Sample',value:'sample',href: false},
          {name: 'Health status',value:'sampleInfo.healthStatus',href: false},
        ],
        tableData: []
      },
      TF_motif: {
        column: [
          {label: 'Motifs of the TF',prop:'motifs'},
          {label: 'All index snv disrupting the selected motif',prop:'snv'},
          // {label: 'Sequence logo',prop:'plot'},
        ],
        tabledata: [
          {
            motifs: ref(''),
            snv: ref(''),
            plot: ref('')
          }
        ]
      },
      TF_chip_seq_binding_table: {
        column:[
          {name: 'Source ID',value:'chip_seq_source',href: true,width: "150"},
          {name: 'Source',value:'data_source',href: false},
          {name: 'TF or other factors',value:'tf',href: false,width: "220"},
          {name: 'ChIP-seq peak',value:'tf_start',href: false},
          {name: 'SNV',value:'snv',href: false},
          {name: 'CpG position',value:'snvCpgAll.cpgPos',href: false},
          // {name: 'Sample',value:'sample_asm',href: false},
          {name: 'Tissue',value:'tissue_type',href: false,width: "110"},
          {name: 'Health status',value:'sampleInfo.healthStatus',href: false},
        ],
        tableData: []
      },
      motifString: [],
      snvSring: [],
      motifLoading: true,
      Motif: ref(''),
      motifOptions:ref([]),
      tfPlot: ref({})
    })
    const tfTable1 = {
      tf: form.tf,
      health: form.health_status.length === 2 ? 'Cancer,Normal' : form.health_status[0],
      tissue: form.asm.tissue,
      motif:form.motif,
      motif_id: data.Motif.value,
      snv:form.snv,
      type:form.type
    }
    const getPlot = (tfName,health_status,tissue,motif,motif_id,snv,type) => {
      data.motifLoading = true
      api.analysis_tf.getPlot(tfName,health_status,tissue,motif,motif_id,snv,type).then(res => {
        let plotdata = res.data.plotdata
        let plotDataType = []
        for (let i = 3; i < plotdata.length; i++) {
          if (!plotDataType.includes(plotdata[i][3])){
            plotDataType.push(plotdata[i][3])
          }
        }
        let plot = {}
        let dataAll = []
        for (let i = 3; i < plotdata.length; i++) {
          for (let j = 0; j < plotDataType.length; j++) {
            if (plotdata[i][3] === plotDataType[j]){
              typeof plot['data'+j] === 'object' ? plot['data'+j]['type']=plotDataType[j] : plot['data'+j] = {type: plotDataType[j],data:[]}
              plot['data'+j]['data'].push([plotdata[i][1],plotdata[i][2]])
            }
          }
          dataAll.push([plotdata[i][1],plotdata[i][2]])
        }
        plot['data'] = dataAll
        plot['type'] = plotDataType
        plot['R'] = plotdata[1][0]
        plot['P'] = plotdata[1][1]
        data.tfPlot=plot
        console.log("plot ===> ",data.tfPlot)
        if (res.data.motifPng === null){
          data.TF_motif.tabledata[0].plot = null
        }else {
          data.TF_motif.tabledata[0].plot = filetool.getUrlByBase64(res.data.motifPng,"image/png")
        }
        data.motifLoading = false
      })
    }
    const getMotif = (tfName,health_status,tissue,motif,snv,type) => {
      api.analysis_tf.getMotif(tfName,health_status,tissue,motif,snv,type).then(res => {
        if (res.data.motif.length>0 &&  res.data.snv.length>0){
          let motifList = []
          let snvList = []
          for (let i = 0; i < res.data.motif.length; i++) {
            if (motifList.indexOf(res.data.motif[i].motif) >= 0){
              continue
            }else {
              motifList.push(res.data.motif[i].motif)
              data.motifOptions.push({value: res.data.motif[i].motif ,label: res.data.motif[i].motif})
            }
          }
          for (let i = 0; i < res.data.snv.length; i++) {
            if (snvList.indexOf(res.data.snv[i].snv) >= 0){
              continue
            }else {
              snvList.push(res.data.snv[i].snv)
            }
          }
          data.Motif = {value: motifList[0] ,label: motifList[0]}
          tfTable1.motif_id = motifList[0]
          tfTable1.tf = res.data.snv[0].tf
          data.TF_motif.tabledata[0].motifs = motifList.join(",")
          data.TF_motif.tabledata[0].snv = snvList.join(",")
          // console.log("motif ===> ",data.motifOptions)
          // console.log("snv ===> ",data.TF_motif.tabledata[0].snv)
          getPlot(tfTable1.tf,tfTable1.health,tfTable1.tissue,tfTable1.motif,data.Motif.value,tfTable1.snv,tfTable1.type)
        }
      })
    }


    watch(()=>data.tfPlot,(value)=>{
      console.log("tfPlot value ===> ",value)
      data.tfPlot = value
    })
    watch(data.Motif,(value)=>{
      data.Motif = value
    })
    watch(data.motifOptions,(value)=>{
      data.motifOptions = value
    })
    watch(data.TFMotifTableHeader,(value)=>{
      data.TFMotifTableHeader = value
    })
    watch(data.TFMotifTableData,(value)=>{
      data.TFMotifTableData = value
    })
    // getPlot(tfTable1.tf,tfTable1.health,tfTable1.tissue,tfTable1.motif)
    getMotif(tfTable1.tf,tfTable1.health,tfTable1.tissue,tfTable1.motif,tfTable1.snv,tfTable1.type)
    return {
      ...toRefs(data),
      form,tfTable1,
      getPlot
    }
  }
}
</script>

<style scoped>
::v-deep .el-collapse-item__header{
  height: 56px;
  background-color: #2185d0;
  color: white;
  border-radius: 2px;
  border-bottom: 0;
}
::v-deep .el-collapse-item{
  border-radius: 5px;
  margin-top: 20px;
  border: solid 2px #2185d0;
}
.card-title{
  padding: 10px;
  font-weight: bold;
  font-size: 20px;
}
.card{
  margin-bottom: 10px;
}
.card-body{
  margin-top: 20px
}
::v-deep .el-descriptions__table{
  height:540px
}
</style>
